#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on May 16, 2014, by Junn
#

from django import forms

from models import Post
from utils.eggs import rename_file
from utils import images, files, eggs, logs
import settings


class PostForm(forms.ModelForm):

    info = forms.CharField(required=False)  #添加此3项为设定required=False
    pic = forms.ImageField(required=False)  #对应表单数据结构
    pic_num = forms.IntegerField(required=False)
    aud = forms.FileField(required=False)
    aud_len = forms.IntegerField(required=False)
    
    def __init__(self, author, family, *args, **kwargs):
        self.author = author
        self.family = family
        return super(PostForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Post
        fields = ('info', 'pic', 'pic_num', 'aud', 'aud_len', )
        
    def clean_info(self):
        info = self.cleaned_data.get('info', '')
        return info.strip()
          
    def clean_pic(self):
        pic = self.cleaned_data.get('pic', '')
        #if pic:
        #    rename_file(pic)
        return pic
        
    def clean_pic_num(self): #图片张数
        data = self.cleaned_data
        pic_num = data.get('pic_num', 0)
        
        # We can't get the pic1 or pic_x object through self.cleaned_data.get('pic1'), so use self.files instead
        if self.files.get('pic') and pic_num < 1:
            pic_num = 1
        if pic_num > 9:
            raise forms.ValidationError(u'图片不能超过9张')
         
        if pic_num > 1:
            for i in range(pic_num-1):
                pic_key = u'pic%s' % (i+1, )
                try: 
                    if not self.files.get(pic_key):
                        raise forms.ValidationError(u'图片参数%s对应的文件对象为空' % pic_key)
                except KeyError, ke:
                    logs.error('Key not found in pics \n %s' % ke)
                    raise forms.ValidationError(u'未找到对应的图片参数: %s' % pic_key)
        
        return pic_num
    
    def clean_aud(self):
        aud = self.cleaned_data.get('aud')
        #if aud:
        #    rename_file(aud)
        return aud    
    
    def clean_aud_len(self):  #TODO: check is digit
        aud_len = self.cleaned_data.get('aud_len', 0)
        return aud_len
    
    def clean(self):
        info = self.cleaned_data.get('info', '')
        pic = self.cleaned_data.get('pic')
        aud = self.cleaned_data.get('aud')
        aud_len = self.cleaned_data.get('aud_len', 0)
        if not info.strip() and not pic and not aud:
            raise forms.ValidationError(u'还没有输入任何内容')
        if aud and not aud_len:
            raise forms.ValidationError(u'缺乏语音长度参数')
        
        return self.cleaned_data
        
    def save(self):
        data = self.cleaned_data
        post = Post(**data)
        post.family = self.family
        post.author = self.author
        post.aud = files.save_audio(data.get('aud'), eggs.gen_uuid1())
        
        # 避免DB写入null值
        if not post.aud:
            post.aud_len = 0
        if not post.pic:
            post.pic_num = 0     
        
        filename_prefix = eggs.gen_uuid1()
        post.pic = images.save_image(self.files.get('pic'), filename_prefix+'.jpg', create_thumb=True)
        
        if post.pic_num > 1: 
            for i in range(post.pic_num-1):
                images.save_image(self.files.get('pic%s' % (i+1, )), '%s_%s.jpg' % (filename_prefix, i+1), create_thumb=True)
        
        post.save()
        return post    
        
        
        
        
        